package com.vedio.service;

import com.vedio.dao.MovieDao;
import com.vedio.entity.Movie;
import com.vedio.mapper.MovieMapper;
import com.vedio.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MovieService implements MovieDao {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2.获取SqlSessionFactory对象，用它执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //3.执行sql
    //List<Product> products = sqlSession.selectList("test.selectAll");
    //获取mapper接口的代理对象
    MovieMapper movieMapper = sqlSession.getMapper(MovieMapper.class);

    public MovieService() throws IOException {
    }

    @Override
    public List<Movie> selectAll() throws IOException {
        List<Movie> movies = movieMapper.selectAll();
        sqlSession.close();
        return movies;
    }

    @Override
    public Movie selectById(Integer id) {
        Movie movie = movieMapper.selectById(id);
        sqlSession.close();
        return movie;
    }

    @Override
    public int add(Movie movie) {
        int result = movieMapper.add(movie);
        sqlSession.close();
        return result;
    }

    @Override
    public int update(Movie movie) {
        int update = movieMapper.update(movie);
        sqlSession.close();
        return update;
    }

    @Override
    public int deleteById(Integer id) {
        int result = movieMapper.deleteById(id);
        sqlSession.close();
        return result;
    }
}
